<?php
    namespace app\api\service;
    use think\Request;
    use think\Cache;
    use think\Exception;
    use app\lib\exception\TokenException;
    use app\lib\exception\ForbiddenException;
    use app\lib\enum\ScopeEnum;

    class Token
    {
        public static function generateToken()
        {
            //32个字符组成随机字符串
            $randChars = getRandChar(32);
            //时间戳
            $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
            //salt 盐
            $salt = config('secure.token_salt');

            return md5($randChars.$timestamp.$salt);
        }
        # 公用方法
        public static function getCurrentTokenVal($key)
        {
            $token = Request::instance()
                     ->header('token');
            $vars = Cache::get($token);
            if(!$vars){
                throw new TokenException();
            }else {
                if(!is_array($vars)){
                    $vars = json_decode($vars, true);
                }
                if(array_key_exists($key, $vars)){
                    return $vars[$key];
                }else{
                    throw new Exception('尝试获取的token不存在');
                }
            }
        }
        public static function getCurrentUid()
        {
            //token
            $uid = self::getCurrentTokenVal('uid');
            return $uid;
        }
        // 权限控制 用户和管理员都可以访问
        public static function needPrimaryScope()
        {
            $scope = self::getCurrentTokenVal('scope');

            if($scope){
                    if($scope >= ScopeEnum::User){
                    return true;
                }
                else {
                    throw new ForbiddenException();
                }
            }
            else {
                
                throw new TokenException();
            }
        }

        // 只有用户可以访问
        public static function needExclusiveScope()
        {
            $scope = self::getCurrentTokenVal('scope');

            if($scope){
                    if($scope == ScopeEnum::User){
                    return true;
                }
                else {
                    throw new ForbiddenException();
                }
            }
            else {
                
                throw new TokenException();
            }
        }
    }